package vip.george.springbootiptools.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import vip.george.springbootiptools.autocofnig.IpToolProperties;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class IpToolService {

    Map<String, Integer> ipMap = new ConcurrentHashMap<>();

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IpToolProperties ipToolProperties;

    public void count() {
        String ip = request.getRemoteAddr();
        if (ipMap.containsKey(ip)) {
            ipMap.put(ip, ipMap.get(ip) + 1);
        } else {
            ipMap.put(ip, 1);
        }
    }


//    @Scheduled(cron = "0/5 * * * * ?")
    //使用Spring EL表达式来获取值（bean名称 + . + 成员变量名）
    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void display() {
        System.out.println();
        if (ipToolProperties.getModel().equals(IpToolProperties.LogModel.DETAIL.getValue())) {
            System.out.println("    IP监控(详细版)：");
            System.out.println("+---------IP --------+---COUNT--+");
            for (Map.Entry<String, Integer> entry : ipMap.entrySet()) {
                String s = String.format("|%18s  |%6d  |", entry.getKey(), entry.getValue());
                System.out.println(s);
            }
            System.out.println("+--------------------+----------+");
        } else if (ipToolProperties.getModel().equals(IpToolProperties.LogModel.SIMPLE.getValue())){
            System.out.println("    IP监控(简洁版)：");
            System.out.println("+---------IP --------+");
            for (String key : ipMap.keySet()) {
                String s = String.format("|%18s  |", key);
                System.out.println(s);
            }
            System.out.println("+--------------------+");
        }


        if (ipToolProperties.getCycleReset()) {
            ipMap.clear();
        }
    }

//    public static void main(String[] args) {
//        IpToolService ipToolService = new IpToolService();
//        ipToolService.display();
//    }
}
